import json

from channels.db import database_sync_to_async
from channels.generic.websocket import AsyncWebsocketConsumer

from .user.models import UserMessage
from .live.models import LiveRoom


class MessagesConsumer(AsyncWebsocketConsumer):
    """处理私信websocket请求"""

    async def connect(self):
        if self.scope['user'].is_anonymous:
            # 拒绝匿名用户连接
            await self.close()
        else:
            # 加入聊天组
            self.scope['all_user'] = []
            self.scope['all_user'].append(self.scope['user'].username)
            await self.channel_layer.group_add(self.scope['url_route']['kwargs']['group'], self.channel_name)
            await self.accept()

    async def receive(self, text_data=None, bytes_data=None):
        """接收到后端发来的私信"""
        if text_data['receive'] not in self.scope['all_user']:
            await self.send(text_data=json.dumps(text_data))  # 发送到接收用户
        else:
            # 如果接受在聊天室中，改变聊天状态为已读
            await self.get_msg(text_data)
            await self.send(text_data=json.dumps(text_data))  # 发送到接收用户

    async def disconnect(self, code):
        """离开聊天组"""
        await self.channel_layer.group_discard(self.scope['url_route']['kwargs']['group'], self.channel_name)

    @database_sync_to_async
    def get_msg(self, text_data):
        msg = UserMessage.objects.get(id=text_data['msg_id'])
        msg.has_read = True
        msg.save()
        return


class GiveMessageConsumer(AsyncWebsocketConsumer):
    """介绍到消息后，推送给接受用户"""

    async def connect(self):
        if self.scope['user'].is_anonymous:
            # 拒绝匿名用户连接
            await self.close()
        else:
            # 加入聊天组
            await self.channel_layer.group_add(self.scope['url_route']['kwargs']['group'], self.channel_name)
            await self.accept()

    async def receive(self, text_data=None, bytes_data=None):
        """接收到后端发来的私信"""
        await self.send(text_data=json.dumps(text_data))  # 发送到接收用户

    async def disconnect(self, code):
        """离开聊天组"""
        await self.channel_layer.group_discard(self.scope['url_route']['kwargs']['group'], self.channel_name)


class LiveRoomConsumer(AsyncWebsocketConsumer):
    """直播间聊天室"""

    async def connect(self):
        # 添加直播间人数
        await self.add_live_people_num(group=self.scope['url_route']['kwargs']['group'])
        # 加入聊天组
        await self.channel_layer.group_add(self.scope['url_route']['kwargs']['group'], self.channel_name)
        await self.accept()

    async def receive(self, text_data=None, bytes_data=None):
        """接收到发来的私信"""
        await self.send(text_data=json.dumps(text_data))

    async def disconnect(self, code):
        """离开聊天组"""
        await self.delete_live_people_num(group=self.scope['url_route']['kwargs']['group'])
        await self.channel_layer.group_discard(self.scope['url_route']['kwargs']['group'], self.channel_name)

    @database_sync_to_async
    def add_live_people_num(self, group):
        lr = LiveRoom.objects.filter(number=group)
        if lr:
            lr[0].hot_num += 1
            lr[0].save()
        return

    @database_sync_to_async
    def delete_live_people_num(self, group):
        lr = LiveRoom.objects.filter(number=group)
        if lr:
            if lr[0].hot_num <= 0:
                lr[0].hot_num = 0
                return
            lr[0].hot_num -= 1
            lr[0].save()
        return
